import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store";
Vue.use(VueRouter);

const routes = [
  // 一级路由
  // 登录
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login"),
  },
  // 首页
  {
    path: "/",
    redirect: "/home",
    name: "layout",
    component: () => import("@/views/layout"),
    children: [
      {
        path: "home",
        name: "home",
        component: () => import("@/views/layout/home.vue"),
      },
      {
        path: "categroy",
        name: "categroy",
        component: () => import("@/views/layout/categroy.vue"),
      },
      {
        path: "cart",
        name: "cart",
        component: () => import("@/views/layout/cart.vue"),
      },
      {
        path: "user",
        name: "user",
        component: () => import("@/views/layout/user.vue"),
      },
    ],
  },
  // 搜索页
  {
    path: "/search",
    name: "search",
    component: () => import("@/views/search"),
  },
  // 搜索列表
  {
    path: "/search/list",
    name: "list",
    component: () => import("@/views/search/list.vue"),
  },
  // 商品详情
  {
    path: "/prodetail",
    name: "prodetail",
    component: () => import("@/views/prodetail"),
  },
  // 结算支付
  {
    path: "/pay",
    name: "pay",
    component: () => import("@/views/pay"),
  },
  // 订单管理
  {
    path: "/myorder",
    name: "myorder",
    component: () => import("@/views/myorder"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
// 前置路由守卫 所有路由在解析前 都会经过全局路由守卫
//to 表示去哪
//from 表示从哪来
//next 通行

// 定义一个数组专门存放所有需要权限的页面
const authUrls = ["/pay", "/myorder"];

router.beforeEach((to, from, next) => {
  if (!authUrls.includes(to.path)) {
    // 判断权限路由是否包含to.path
    next();
    return;
  }

  // 是权限页面需要判断
  const token = store.getters.token;
  if (token) {
    next();
  } else {
    next("/login");
  }
});

export default router;
